<template>
	<div class="x-addition-box">
		<flexbox class="x-head">
			<CrmRelativeCell
				v-if="isShowRelative"
				:item="relativeItem"
				:value="dataValue"
				:index="index"
				:query="query"
				:disabled="cellDisabled || disabled"
				:radio="radio"
				class="supplier"
				@value-change="handleValueChange"
			/>
			<el-button
				:disabled="cellDisabled || disabled"
				type="primary"
				@click="handleAdd"
				>新增一条</el-button
			>
		</flexbox>
		<el-table
			:data="dataValue"
			:max-height="250"
			stripe
			size="mini"
			border
			style="width: 100%"
			class="x-smoll-table"
		>
			<el-table-column
				v-if="error.size > 0"
				:fixed="true"
				label="错误信息"
				min-width="150"
				max-width="200"
			>
				<div slot-scope="scope" class="x-error">
					{{ error.get(scope.row) || '' }}
				</div>
			</el-table-column>
			<el-table-column
				v-for="(column, index) in fieldList"
				:key="index"
				:prop="column.field"
				:label="column.name"
				:min-width="column.item.data.width || 150"
				show-overflow-tooltip
			>
				<div slot="header" slot-scope="scope">
					<span v-show="column.item.data.isNull" style="color: red">*</span>
					{{ scope.column.label }}
				</div>
				<template slot-scope="scope">
					<component
						:is="column.item.data.formType | typeToComponentName"
						:value="scope.row[column.field]"
						:index="index"
						:item="column.item"
						:radio="item.radio"
						:disabled="column.item.disabled"
						:filterable="column.item.filterable"
						:multiple="column.item.multiple"
						:query="{ supplier_id: scope.row.supplierId }"
						@value-change="filterValueChange(scope, arguments)"
					/>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>
import {
	regexIsCRMNumber,
	regexIsCRMMoneyNumber,
	regexIsCRMMobile,
	regexIsCRMEmail,
	objDeepCopy
} from '@/utils'
import {
	XhInput,
	XhTextarea,
	XhSelect,
	XhMultipleSelect,
	XhDate,
	XhDateTime,
	XhUserCell,
	XhStructureCell,
	XhFiles,
	XhProuctCate,
	XhProduct,
	XhBusinessStatus,
	XhBusinessInsureType,
	XhCustomerAddress,
	XhReceivablesPlan, // 对账与结算计划期数
	XhEdit,
	XhGroup
} from '@/components/createCom'
import CrmRelativeCell from './CrmRelativeCell'
import crmTypeModel from '@/views/customermanagement/model/crmTypeModel'
import { filedValidates } from '@/api/customermanagement/common'
import arrayMixin from '@/components/createCom/arrayMixin'
import { v4 as uuid } from 'uuid'
export default {
	components: {
		// CrmRelativeCell,
		CrmRelativeCell,
		XhInput,
		XhTextarea,
		XhSelect,
		XhMultipleSelect,
		XhDate,
		XhDateTime,
		XhUserCell,
		XhStructureCell,
		XhFiles,
		XhProuctCate,
		XhProduct,
		XhBusinessStatus,
		XhBusinessInsureType,
		XhCustomerAddress,
		XhReceivablesPlan, // 对账与结算计划期数
		XhEdit,
		XhGroup
	},
	filters: {
		typeToComponentName(formType) {
			if (
				formType == 'text' ||
				formType == 'number' ||
				formType == 'floatnumber' ||
				formType == 'mobile' ||
				formType == 'email'
			) {
				return 'XhInput'
			} else if (formType == 'textarea') {
				return 'XhTextarea'
			} else if (
				formType == 'select' ||
				formType == 'business_status' ||
				formType == 'brand'
			) {
				return 'XhSelect'
			} else if (formType == 'checkbox') {
				return 'XhMultipleSelect'
			} else if (formType == 'date') {
				return 'XhDate'
			} else if (formType == 'datetime') {
				return 'XhDateTime'
			} else if (formType == 'user') {
				return 'XhUserCell'
			} else if (formType == 'structure') {
				return 'XhStructureCell'
			} else if (formType == 'file') {
				return 'XhFiles'
			} else if (
				formType == 'contacts' ||
				formType == 'customer' ||
				formType == 'contract' ||
				formType == 'business' ||
				formType == 'suppliercontacts' ||
				formType == 'payable'
			) {
				return 'CrmRelativeCell'
			} else if (formType == 'category') {
				// 产品类别
				return 'XhProuctCate'
			} else if (formType == 'business_type') {
				// 订单类别
				return 'XhBusinessStatus'
			} else if (formType == 'business_insure_type') {
				return 'XhBusinessInsureType'
			} else if (formType == 'product') {
				return 'XhProduct'
			} else if (formType == 'map_address') {
				return 'XhCustomerAddress'
			} else if (formType == 'receivables_plan') {
				return 'XhReceivablesPlan'
			} else if (formType == 'wangEditor') {
				return 'XhEdit'
			} else if (formType == 'group') {
				return 'XhGroup'
			}
		}
	},
	mixins: [arrayMixin],
	props: {
		radio: {
			// 是否单选
			type: Boolean,
			required: true
		},
		// 获取列表的查询条件
		query: {
			type: Object,
			default: () => {}
		},
		crmType: String
	},
	data() {
		return {
			error: new Map(),
			rules: {}
		}
	},
	computed: {
		fieldList() {
			const fieldList = this.item.data.append.map((item) => {
				return {
					name: item.name,
					field: item.fieldName,
					item: this.getcrmRulesAndModel(item)
				}
			})
			return fieldList
		},
		appendFieldObj() {
			var { append } = this.item.data
			return append.reduce((pre, item, index) => {
				pre[item.fieldName] = this.getcrmRulesAndModel(item).value
				return pre
			}, {})
		},
		isShowRelative() {
			return this.item.data.url // 查询crmRelativeTable的地址
		},
		// 非多选情况下 控制禁用
		cellDisabled() {
			return !this.item.data.isMutiple && this.dataValue.length > 0
		},
		relativeItem() {
			const item = JSON.parse(JSON.stringify(this.item))
			item.data.formType = 'relation'
			return item
		}
	},
	watch: {
		value: {
			handler(val) {
				this.dataValue = JSON.parse(JSON.stringify(val))
			},
			deep: true,
			immediate: true
		}
	},
	methods: {
		handleValueChange(data) {
			// var key = this.item.data.formType + 'Id'

			this.dataValue = data.value.map((item) => {
				return {
					...JSON.parse(JSON.stringify(this.appendFieldObj)),
					...item
				}
			})
			this.valueChange(this.dataValue)
		},
		// 新增一条
		handleAdd() {
			var key = this.item.data.formType + 'Id'
			this.dataValue.push({
				...JSON.parse(JSON.stringify(this.appendFieldObj))
			})
			this.valueChange(this.dataValue)
		},
		filterValueChange(scope, [data]) {
			// console.log(scope.column.property, data.value)
			scope.row[scope.column.property] = data.value
			// 下拉列表中relative字段携带了关联值
			if (data.item.data.formType === 'select') {
				const { relative } = data.item.data.setting.find(
					(set) => set.value === data.value
				)
				if (relative) {
					for (const key in relative) {
						scope.row[key] = relative[key]
					}
				}
			}
			this.valueChange(this.dataValue)
		},
		getcrmRulesAndModel(item) {
			item.uuid = uuid()
			this.rules[item.fieldName] = this.getItemRulesArrayFromItem(item)

			if (item.formType == 'group') {
				var params = {}
				params['value'] = {} // 校验结果值 默认{} 待内部验证后 通过value-change返回正确的值
				params['childrens'] = item.childrens || []
				params['key'] = item.fieldName
				params['data'] = item
				params['disabled'] = item.disabled // 是否可交互
				return params
			} else if (
				item.formType == 'select' ||
				item.formType == 'business_status' ||
				item.formType == 'brand'
			) {
				var params = {}
				params['filterable'] = Boolean(item.filterable) // 下拉框可搜索
				params['value'] = item.value
				params['key'] = item.fieldName
				params['data'] = item
				params['disabled'] = false // 是否可交互
				return params
			} else if (item.formType == 'suppliercontacts') {
				var params = {}
				params['key'] = item.fieldName
				params['data'] = item
				params['radio'] = item.radio !== false
				params['createable'] = item.createable !== false
				params['styleIndex'] = '1'
				params['multiple'] = Boolean(item.multiple)
				params['placeholder'] = item.placeholder
				params['value'] = item.value || []
				return params
			} else {
				var params = {}
				var value = item.value
				if (
					item.formType == 'user' ||
					item.formType == 'structure' ||
					item.formType == 'file' ||
					item.formType == 'category' ||
					item.formType == 'customer' ||
					item.formType == 'business' ||
					item.formType == 'contract'
				) {
					params['value'] = value ? objDeepCopy(value) : []
				} else {
					params['value'] = value || ''
				}
				params['key'] = item.fieldName
				params['data'] = item
				params['disabled'] = false // 是否可交互
				return params
			}
		},
		getItemRulesArrayFromItem(item) {
			var tempList = []
			// 验证必填
			if (item.isNull == 1) {
				if (item.formType == 'category') {
					tempList.push({
						required: true,
						message: item.name + '不能为空',
						trigger: []
					})
				} else {
					tempList.push({
						required: true,
						message: item.name + '不能为空',
						trigger: ['blur', 'change']
					})
				}
			}

			// 验证唯一
			if (item.isUnique == 1) {
				var validateUnique = (rule, value, callback) => {
					if (!value && rule.item.isNull == 0) {
						callback()
					} else {
						var validatesParams = {}
						validatesParams.name = item.name
						validatesParams.val = value
						validatesParams.types = crmTypeModel[this.crmType]
						if (this.action.type == 'update') {
							validatesParams.id = this.action.id
						}
						filedValidates(validatesParams)
							.then((res) => {
								callback()
							})
							.catch((error) => {
								callback(new Error(error.error ? error.error : '验证出错'))
							})
					}
				}
				tempList.push({
					validator: validateUnique,
					item: item
				})
			}

			// 特殊字符
			if (item.formType == 'number') {
				var validateCRMNumber = (rule, value, callback) => {
					if (!value || value == '' || regexIsCRMNumber(value)) {
						callback()
					} else {
						callback(new Error('数字的整数部分须少于12位，小数部分须少于4位'))
					}
				}
				tempList.push({
					validator: validateCRMNumber,
					item: item
				})
			} else if (item.formType == 'floatnumber') {
				var validateCRMMoneyNumber = (rule, value, callback) => {
					if (!value || value == '' || regexIsCRMMoneyNumber(value)) {
						callback()
					} else {
						callback(new Error('货币的整数部分须少于10位，小数部分须少于2位'))
					}
				}
				tempList.push({
					validator: validateCRMMoneyNumber,
					item: item,
					trigger: ['blur']
				})
			} else if (item.formType == 'mobile') {
				var validateCRMMobile = (rule, value, callback) => {
					if (!value || value == '' || regexIsCRMMobile(value)) {
						callback()
					} else {
						callback(new Error('手机格式有误'))
					}
				}
				tempList.push({
					validator: validateCRMMobile,
					item: item,
					trigger: ['blur']
				})
			} else if (item.formType == 'email') {
				var validateCRMEmail = (rule, value, callback) => {
					if (!value || value == '' || regexIsCRMEmail(value)) {
						callback()
					} else {
						callback(new Error('邮箱格式有误'))
					}
				}
				tempList.push({
					validator: validateCRMEmail,
					item: item,
					trigger: ['blur']
				})
			} else if (item.formType == 'product') {
				var validateCRMProduct = (rule, value, callback) => {
					if (value && value.product && value.product.length) {
						callback()
					} else {
						callback(new Error('请添加产品'))
					}
				}
				tempList.push({
					validator: validateCRMProduct,
					item: item,
					trigger: ['blur']
				})
			} else if (item.formType == 'wangEditor') {
				var validateCRMWangEditor = (rule, value, callback) => {
					if (item.isNull == 1) {
						if (value && value.html) {
						} else {
							callback(new Error('请编辑内容'))
							return
						}
					}
					if (item.isFile == 1) {
						if (value && value.files.length) {
						} else {
							callback(new Error('请上传附件'))
							return
						}
					}
					callback()
				}
				tempList.push({
					validator: validateCRMWangEditor,
					item: item
				})
			} else if (item.formType == 'group') {
				var validateCRMGroup = (rule, value, callback) => {
					if (Object.keys(value).length == 0) {
						callback(new Error('内容有误'))
						return
					}
					callback()
				}
				tempList.push({
					validator: validateCRMGroup,
					item: item
				})
			}
			return tempList
		},
		validate() {
			if (this.item.data.isNull == 1) {
				if (this.value.length == 0) {
					return {
						result: false,
						message: this.item.name + '不能为空'
					}
				}
				this.error.clear()
				let valid = true
				this.dataValue.forEach((row, index) => {
					Object.keys(row).forEach((key) => {
						const ruleArr = this.rules[key]
						if (ruleArr) {
							var name = this.fieldList.find(
								(column) => column.field == key
							).name
							ruleArr.forEach((rule) => {
								if (rule.required && row[key] === '') {
									var msg = this.error.get(row) || ''
									msg && (msg += ', ')
									this.error.set(row, msg + rule.message)
									valid = false
								}
								if (rule.validator) {
									rule.validator(rule, row[key], (error) => {
										if (error) {
											var msg = this.error.get(row) || ''
											msg && (msg += ', ')
											this.error.set(row, msg + rule.message)
											valid = false
										}
									})
								}
							})
						}
					})
				})
				this.$forceUpdate()
				if (!valid) {
					return {
						result: false,
						message: '请修改错误信息'
					}
				}
			}
			return {
				result: true
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.x-addition-box {
}
.x-head {
	padding: 3px;
	border: 1px solid #e6e6e6;
	border-bottom-width: 0;
	.supplier {
		flex: 1;
		margin-right: 3px;
	}
}
.x-error {
	color: red;
}
::v-deep {
	.x-smoll-table {
		.el-table__header th {
			padding: 0;
		}
		.el-table__body td {
			padding: 5px 0;
		}
		.el-input__inner,
		.el-input__inner:focus,
		.el-textarea__inner,
		.el-textarea__inner:focus {
			border-color: #ddd !important;
		}
	}
	.xh-input .el-input__inner {
		border-color: #e6e6e6 !important;
	}
}
</style>
